//
//  CXKeyboardTextView.swift
//  CXSwiftWB
//
//  Created by meidaeriOS on 2017/6/7.
//  Copyright © 2017年 meidaer. All rights reserved.
//

import UIKit

class CXKeyboardTextView: UITextView {

    func insertEmotion(_ emotion: KeyboardEmoticon) {
        
        if let tempEmojiStr = emotion.emoticonStr {
            // 取出光标所在的位置
            let range = selectedTextRange!
            replace(range, withText: tempEmojiStr)
            return
        }
        
        if let tempPngPath = emotion.pngPath {
            let attrMSTr = NSMutableAttributedString(attributedString: attributedText)
            
            let attachment = XMGKeyboardAttachment()
            attachment.emoticonChs = emotion.chs
            let fontHeight = font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
            
            attachment.image = UIImage(contentsOfFile: tempPngPath)
            
            let imageAttrStr = NSAttributedString(attachment: attachment)
            
            let range = selectedRange
            
            attrMSTr.replaceCharacters(in: range, with: imageAttrStr)
            
            // 重新确定光标的位置
            selectedRange = NSMakeRange(range.location + 1, 0)
            
            font = UIFont.systemFont(ofSize: 18)
        }
        
        if emotion.isRemoveButton {
            deleteBackward()
        }
    }
    
    func emotionStr() -> String {
        let range = NSRange(location: 0, length: attributedText.length)
        
        var strM = String()
        
        attributedText.enumerateAttributes(in: range, options: .init(rawValue: 0)) { (dict, range, _) in
            if let tempAttachment = dict["NSAttachment"] as? XMGKeyboardAttachment {
                strM += tempAttachment.emoticonChs!
            } else {
                strM += (self.text as NSString).substring(with: range)
            }
        }
        return strM
    }

}
